package com.example.springboot.service;

import com.example.springboot.entities.User;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@CacheConfig(cacheNames = "userService")
@Service
public class UserService {
    /**
     * cacheNames:缓存名字
     * key:缓存容器中的key值，返回值是value值
     *
     * @param id
     * @return
     */
//    @Cacheable(cacheNames = "user")
//    @Cacheable(value = "user")
    @Cacheable(cacheNames = "user", key = "#id")
    public User getUserById(Integer id) {
        User user = new User("你好啊", 2);
        user.setWorkTime(LocalDateTime.now());
        return user;
    }

    /**
     * cacheNames:缓存名字
     * key:缓存容器中的key值，返回值是value值
     *
     * @param id
     * @return
     */
//    @Cacheable(cacheNames = "findUser")
//    @Cacheable(value = "findUser")
    @Cacheable(cacheNames = {"aa","bbb"}, key = "#condition.id")
    public List<User> findUser(User condition) {
        List<User> users = new ArrayList<>();
        System.out.println("findUser");
        return users;
    }

    //    @CachePut(cacheNames = "user", key = "#user.id")
    @CachePut(/*cacheNames = "user", */key = "#result.id")
    public User updateUser(User user) {
        System.out.println("updateUser");
        return user;
    }

    /**
     * allEntries会将缓存中的数据全部清空
     *
     * @param id
     * @return
     */
    @CacheEvict(cacheNames = "user", key = "#id", allEntries = true)
//    @CacheEvict(/*cacheNames = "user",*/ key = "#id")
    public Integer deleteUserById(Integer id) {
        System.out.println("deleteUserById");
        return id;
    }
}
